package com.shizhanzhe.qdd;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.qdd.apprentice.ApprenticeFragment;
import com.shizhanzhe.qdd.base.BaseActivity;
import com.shizhanzhe.qdd.base.UserBean;
import com.shizhanzhe.qdd.forward.ForwardFragment;
import com.shizhanzhe.qdd.home.HomeFragment;
import com.shizhanzhe.qdd.url.Path;
import com.shizhanzhe.qdd.utils.AD;
import com.shizhanzhe.qdd.utils.AdPreference;
import com.shizhanzhe.qdd.utils.BnfStartupAdPageDto;
import com.shizhanzhe.qdd.utils.DownListener;
import com.shizhanzhe.qdd.utils.DownloadUtil;
import com.shizhanzhe.qdd.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.qdd.utils.SharedPreferencesUtils;
import com.shizhanzhe.qdd.utils.Util;
import com.tencent.bugly.beta.Beta;

import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {
    private long exitTime = 0;
    @BindView(R.id.frame_layout)
    LinearLayout frameLayout;
    @BindView(R.id.navigation)
    BottomNavigationView navigation;

    private HomeFragment homeFragment;
    private ForwardFragment forwardFragment;
    private ApprenticeFragment apprenFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ImmersionBar.with(this).statusBarColor(R.color.them).init();
        Beta.init(getApplicationContext(), false);


    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        forwardFragment = new ForwardFragment();
        fragmentTransaction.add(R.id.frame_layout, forwardFragment);
        fragmentTransaction.commit();
        navigation.setItemIconTintList(null);
        navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                hideAllFragment(transaction);
                switch (menuItem.getItemId()) {
                    case R.id.action_share:
                        if (forwardFragment == null) {
                            forwardFragment = new ForwardFragment();
                            transaction.add(R.id.frame_layout, forwardFragment);
                        } else {
                            transaction.show(forwardFragment);
                        }
                        transaction.commit();

                        return true;
                    case R.id.action_apprenctice:
                        if (apprenFragment == null) {
                            apprenFragment = new ApprenticeFragment();
                            transaction.add(R.id.frame_layout, apprenFragment);
                        } else {
                            transaction.show(apprenFragment);
                        }
                        transaction.commit();

                        return true;
                    case R.id.action_my:
                        if (homeFragment == null) {
                            homeFragment = new HomeFragment();
                            transaction.add(R.id.frame_layout, homeFragment);
                        } else {
                            transaction.show(homeFragment);
                        }
                        homeFragment.setHomeListener(new HomeFragment.HomeListener() {
                            @Override
                            public void homeclick(int homeinto) {
                                switch (homeinto){
                                    case 1:
                                        //分享
                                        hideAllFragment(transaction);
                                        navigation.setSelectedItemId(R.id.action_share);
                                        break;
                                    case 2:
                                        //收徒
                                        hideAllFragment(transaction);
                                        navigation.setSelectedItemId(R.id.action_apprenctice);
                                        break;
                                    default:
                                }
                            }
                        });
                        transaction.commit();
                        return true;
                    default:
                        break;
                }
                return false;
            }
        });
        OkHttpDownloadJsonUtil.downloadJson(this, Path.BASE_URL+"/index.php/index/index/activity", new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    List<AD.DataBean> list = gson.fromJson(json, AD.class).getData();
                    if (!list.isEmpty()) {
                        AD.DataBean ad = list.get(0);
                        if (list.size() > 1) {
                            ad = list.get(new Random().nextInt(list.size()));
                        }
                        AdPreference.getInstance().saveStartupAdPage(new BnfStartupAdPageDto(Path.BASE_URL + ad.getGaopic(), ad.getGaourl(), "1536809117"));
                        new DownloadUtil().downloadImg(Environment.getExternalStorageDirectory() + "/MFAd/", Path.BASE_URL + ad.getGaopic(), new DownListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onProgress(int currentLength) {

                            }

                            @Override
                            public void onFinish(String localPath) {

                            }

                            @Override
                            public void onFailure() {
                                AdPreference.getInstance().clear();
                            }
                        });

                    }
                } catch (Exception e) {
                }
            }
        });
    }

    @Override
    protected void getData() {
        UserBean.uid = (int) SharedPreferencesUtils.getParam(this, "uid", 0);
        UserBean.pid = (int) SharedPreferencesUtils.getParam(this, "pid", 0);
        UserBean.mobile = (String) SharedPreferencesUtils.getParam(this, "mobile", "");
        UserBean.headimg = (String) SharedPreferencesUtils.getParam(this, "headimg", "");
        UserBean.nickname = (String) SharedPreferencesUtils.getParam(this, "nickname", "");
        UserBean.balance = (String) SharedPreferencesUtils.getParam(this,"balance","0.0");
        UserBean.inviteurl = (String) SharedPreferencesUtils.getParam(this,"inviteurl","");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
                return;
            }
        }
        if (UserBean.uid!=0){
            inviteUrl();
        }

    }
    private void inviteUrl(){
        OkHttpDownloadJsonUtil.downloadJson(this, "http://suo.im/api.php?url=" + Path.BASE_URL + "/index.php/index/index/fxb_register?pid=" + UserBean.uid
                , new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        SharedPreferencesUtils.setParam(MainActivity.this,"inviteurl",json);
                        UserBean.inviteurl = json;
                        loadService.showSuccess();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserBean.uid!=0 && "".equals(UserBean.inviteurl)){
            inviteUrl();
        }
    }

    /**
     * 隐藏所有Fragment
     *
     * @param transaction
     */

    public void hideAllFragment(FragmentTransaction transaction) {
        if (forwardFragment != null) {
            transaction.hide(forwardFragment);
        }
        if (apprenFragment != null) {
            transaction.hide(apprenFragment);
        }
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
            Process.killProcess(Process.myPid());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }



}
